import axios from 'axios'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress'

export function _isType (t) {
  return Object.prototype.toString
    .call(t)
    .slice(8, -1)
    .toLowerCase()
}

export function _saveLocalStorage (key, value) {
  if (_isType(value) === 'string') {
    localStorage.setItem(key, value)
  } else {
    let Info = JSON.stringify(value)
    localStorage.setItem(key, Info)
  }
}

export function _getLocalStorage (item) {
  return localStorage.getItem(item)
}

export function _clearStorage () {
  localStorage.clear()
}

export function _getCookie (cName) {
  let cStart, cEnd
  if (document.cookie.length > 0) {
    cStart = document.cookie.indexOf(cName + '=')
    if (cStart !== -1) {
      cStart = cStart + cName.length + 1
      cEnd = document.cookie.indexOf(';', cStart)
      if (cEnd === -1) cEnd = document.cookie.length
      return document.cookie.slice(cStart, cEnd)
    }
  }
  return ''
}

export function _keyMirror (obj) {
  if (obj instanceof Object) {
    var _obj = Object.assign({}, obj)
    var _keyArray = Object.keys(obj)
    _keyArray.forEach(key => {
      _obj[key] = key
      return true
    })
    return _obj
  }
}

export function _isArrayFn (value) {
  if (typeof Array.isArray === 'function') {
    return Array.isArray(value)
  } else {
    return Object.prototype.toString.call(value) === '[object Array]'
  }
}

export function _pagination (pageNo, pageSize, array) {
  let offset = (pageNo - 1) * pageSize
  return offset + pageSize >= array.length
    ? array.slice(offset, array.length)
    : array.slice(offset, offset + pageSize)
}

export function checkCode (val) {
  // let p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  // let factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  // let parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
  // let code = val.substring(17)
  // if (p.test(val)) {
  //   let sum = 0
  //   for (let i = 0; i < 17; i++) {
  //     sum += val[i] * factor[i]
  //   }
  //   if (parity[sum % 11] === Number(code.toUpperCase())) {
  //     return true
  //   }
  // }
  // return false
  let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (reg.test(val) === true) {
    // alert('身份证输入合法')
    return true
  }
}

export function _checkIdNum (rule, value, callback) {
  // const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (value === '' || value === null || value === undefined) {
    callback()
  } else {
    if (!checkCode(value)) {
      return callback(new Error('证件号码不正确'))
    } else {
      callback()
    }
  }
}

export function _checkQQ (rule, value, callback) {
  if (value === '' || value === null || value === undefined) {
    callback()
  } else {
    if (/^[1-9][0-9]{4,10}$/.test(value)) {
      callback()
    } else {
      callback(new Error('输入正确的QQ号'))
    }
  }
}

export function _checkSn (rule, value, callback) {
  if (value === '' || value === null || value === undefined) {
    callback()
  } else {
    if (/^[0-9a-zA-Z]*$/g.test(value)) {
      callback()
    } else {
      callback(new Error('只能输入字母或数字'))
    }
  }
}

export function _checkMobilePhone (rule, value, callback) {
  if (value === '' || value === null || value === undefined) {
    callback()
  } else {
    if (
      /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[01235678]|18[0-9]|19[189])\d{8}$/.test(
        value
      )
    ) {
      callback()
    } else {
      callback(new Error('电话号码格式不正确'))
    }
  }
}
export function _checkEmail (rule, value, callback) {
  if (value === '' || value === null || value === undefined) {
    callback()
  } else {
    if (/\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(value)) {
      callback()
    } else {
      callback(new Error('邮箱格式不正确'))
    }
  }
}
// 验证银行卡号
export function _checkbankNum (rule, value, callback) {
  if (!value) {
    return callback(new Error('请输入银行卡号'))
  }
  setTimeout(() => {
    if (!Number(value)) {
      callback(new Error('只能填写数字'))
    } else {
      callback()
    }
  }, 200)
}
// 验证亲属人数
export function _checkPeopleCount (rule, value, callback) {
  if (!value) {
    return callback(new Error('请输入直系亲属人数'))
  }
  setTimeout(() => {
    if (!Number(value)) {
      callback(new Error('只能填写数字'))
    } else {
      callback()
    }
  }, 200)
}
// 验证座机
export function _checFamilyPhone (rule, value, callback) {
  if (!value) {
    return callback(new Error('电话号码不能为空'))
  } else if (value.toString().length > 12) {
    return callback(new Error('请填写正确的电话号码'))
  }
  setTimeout(() => {
    if (!Number(value)) {
      callback(new Error('只能填写数字'))
    } else {
      callback()
    }
  }, 200)
}
// 验证非必须号码
export function _checNoNeedPhone (rule, value, callback) {
  if (!value) {
    callback()
  } else if (value.toString().length > 12) {
    return callback(new Error('请填写正确的电话号码'))
  }
  setTimeout(() => {
    if (!Number(value)) {
      callback(new Error('只能填写数字'))
    } else {
      callback()
    }
  }, 200)
}
export function routerPrevName (userType) {
  let prevName = null
  if (userType === 2) {
    prevName = 'school'
    return prevName
  } else if (userType === 3) {
    prevName = 'college'
    return prevName
  } else if (userType === 4) {
    prevName = 'counsellor'
    return prevName
  }
}
/* 上传地址全局管理 */
export function prodUrl (url) {
  if (window.location.href.indexOf('localhost') > -1) {
    return url
  } else {
    let rootPath = window.location.href.split('/')[2]
    return (
      'http://' +
      rootPath +
      '/zuul/' +
      window.location.href.split('/')[3] +
      '/' +
      url
    )
  }
}
// 下载
export function downloadFile (fileName, url) {
  let downloadUrl = url
  let a = document.createElement('a')
  a.download = fileName
  a.href = downloadUrl
  a.style.position = 'absolute'
  document.body.appendChild(a)
  a.click()
  // const ieDown = url => {
  //   window.open(url)
  // }

  // const isIE = () => {
  //   const explorer = window.navigator.userAgent
  //   return (
  //     explorer.indexOf('MSIE') >= 0 ||
  //     explorer.indexOf('Trident/7.0') >= 0 ||
  //     explorer.indexOf('Edge') >= 0
  //   )
  // }
  // if (isIE()) {
  //   ieDown(url)
  // } else {
  //   const aLink = document.createElement('a')
  //   const evt = document.createEvent('MouseEvents')
  //   // var evt = document.createEvent("HTMLEvents")
  //   evt.initMouseEvent(
  //     'click',
  //     true,
  //     false,
  //     window,
  //     0,
  //     0,
  //     0,
  //     0,
  //     0,
  //     false,
  //     false,
  //     false,
  //     false,
  //     0,
  //     null
  //   )
  //   aLink.download = fileName
  //   aLink.href = url
  //   aLink.dispatchEvent(evt)
  // }
}

export function downLoadFiles (url, queryObj = {}, fileName = '文件下载', callBack) {
  axios.post(`${url}/`, queryObj, {
    responseType: 'arraybuffer'
  }).then(res => {
    NProgress.done()
    if (res.headers['error-message']) {
      // 截取响应头error-message抛出异常信息
      const message = decodeURI(res.headers['error-message'])
      Message.error(message)
      return false
    }
    const blob = new Blob([res.data], {
      type: ''
    })
    if (window.navigator.msSaveOrOpenBlob) {
      // 兼容IE10
      navigator.msSaveBlob(blob, fileName)
    } else {
      // chrome/firefox
      let aTag = document.createElement('a')
      document.body.appendChild(aTag)
      aTag.download = fileName
      aTag.href = URL.createObjectURL(blob)
      aTag.click()
      document.body.removeChild(aTag)
      URL.revokeObjectURL(aTag.href) // 释放blob对象
      typeof callBack === 'function' ? callBack() : Message.success('下载成功')
    }
  })
}
// 学籍状态
export function studentStatus (type) {
  let statusObj = null
  if (parseInt(type) === 0) {
    statusObj = '正常'
    return statusObj
  } else if (parseInt(type) === 1) {
    statusObj = '休学'
    return statusObj
  } else if (parseInt(type) === 2) {
    statusObj = '退学'
    return statusObj
  } else if (parseInt(type) === 4) {
    statusObj = '毕业'
    return statusObj
  } else {
    statusObj = null
    return statusObj
  }
}

export function cover (dest, src) {
  Object.keys(dest).forEach(item => {
    dest[item] = src[item]
  })
  return dest
}
// 文件下载，默认post请求.
export function downLoadStream (
  url,
  params = {},
  fileName = '文件下载',
  before,
  callBack
) {
  console.log(before)
  if (typeof before === 'function') before()
  axios
    .post(`${url}/`, params, {
      responseType: 'arraybuffer'
    })
    .then(res => {
      NProgress.done()
      if (res.headers['error-message']) {
        // 截取响应头error-message抛出异常信息
        const message = decodeURI(res.headers['error-message']) // 解决中文乱码问题,需后端编码配合。
        // Message.error(message)
        typeof callBack === 'function'
          ? callBack(message)
          : Message.error(message) // 错误信息
      } else {
        const blob = new Blob([res.data], {
          type: ''
        })
        if (window.navigator.msSaveOrOpenBlob) {
          // 兼容IE10及以上
          navigator.msSaveBlob(blob, fileName)
        } else {
          // chrome/firefox
          let aTag = document.createElement('a')
          document.body.appendChild(aTag) // 如果不append进去火狐下载将无反应.
          aTag.download = fileName
          aTag.href = URL.createObjectURL(blob)
          aTag.click()
          document.body.removeChild(aTag)
          URL.revokeObjectURL(aTag.href) // 释放blob对象
          typeof callBack === 'function'
            ? callBack()
            : Message.success('下载成功') // 成功信息
        }
      }
    })
}
// 省份证件号码
export function isCardNo (cardNumber) {
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (reg.test(cardNumber) === false) {
    return false
  } else {
    return true
  }
}
// 手机号码
export function isMobilePhone (phoneNumber) {
  var reg = /0?(13|14|15|16|17|18|19)[0-9]{9}/
  if (reg.test(phoneNumber) === false) {
    return false
  } else {
    return true
  }
}
// 邮箱
export function isEmailNum (email) {
  var reg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
  if (reg.test(email) === false) {
    return false
  } else {
    return true
  }
}
// 护照
export function isPassPort (passPort) {
  const reg = /^1[45][0-9]{7}|([P|p|S|s]\d{7})|([S|s|G|g]\d{8})|([Gg|Tt|Ss|Ll|Qq|Dd|Aa|Ff]\d{8})|([H|h|M|m]\d{8，10})$/
  if (reg.test(passPort) === false) {
    return false
  } else {
    return true
  }
}
// QQ
export function isQQNum (qq) {
  var reg = /[1-9]([0-9]{5,11})/
  if (reg.test(qq) === false) {
    return false
  } else {
    return true
  }
}
export function checkSpecialName (val) {
  var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】><》《‘；：”“'。，、？]")
  return reg.test(val)
}
// 导出文件流
export function exportFile (url, method, body, fileName) {
  axios.defaults.baseURL = process.env.BASE_URL
  axios({
    url,
    method: method,
    data: body,
    responseType: 'blob'
  }).then(res => {
    if (res.headers['error_message']) {
      const message = decodeURI(res.headers['error_message']) // 解决中文乱码问题
      Message.error(message)
    } else if (URL) {
      // 解决大文件下载失败
      let a = null
      var blob = res.data
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE10及以上
        navigator.msSaveBlob(blob, fileName || `导出信息.xls`)
        return
      }
      if (document.getElementById('downLoad')) {
        a = document.getElementById('downLoad')
        a.href = URL.createObjectURL(blob)
        a.download = fileName || `导出信息.xls`
        a.click()
      } else {
        a = document.createElement('a')
        a.id = 'downLoad'
        a.href = URL.createObjectURL(blob)
        a.download = fileName || `导出信息.xls`
        a.style.position = 'absolute'
        document.body.appendChild(a)
        a.click()
      }
    } else {
      let blob = res.data
      var reader = new FileReader()
      reader.readAsDataURL(blob)
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE10及以上
        navigator.msSaveBlob(blob, fileName || `导出信息.xls`)
      } else {
        reader.onload = function (e) {
          let a = null
          if (document.getElementById('downLoad')) {
            a = document.getElementById('downLoad')
            a.href = e.target.result
            a.download = fileName || `导出信息.xls`
            a.click()
          } else {
            a = document.createElement('a')
            a.id = 'downLoad'
            a.href = e.target.result
            a.download = fileName || `导出信息.xls`
            // Message({type: 'success', message: '开始下载'})
            a.style.position = 'absolute'
            document.body.appendChild(a)
            a.click()
          }
        }
      }
    }
    NProgress.done()
  })
}
